# app.py (完整，可直接覆盖)
from flask import Flask, request, jsonify, redirect, url_for
from config import Config, db
from models import House  # 确保 models.py 在项目中并包含 House 模型
from sqlalchemy import func

# 创建 Flask app（只创建一次）
app = Flask(__name__, static_folder='static', static_url_path='/static')
app.config.from_object(Config)
db.init_app(app)

# 注册蓝图（请确保这些模块存在）
# 如果某些模块在你的项目不存在，请移除对应行或创建占位蓝图文件。
try:
    from page.index import index_page
    app.register_blueprint(index_page, url_prefix='/')
except Exception as e:
    print("Warning: index_page blueprint import/register failed:", e)

try:
    from page.user import user_page
    app.register_blueprint(user_page, url_prefix='/')
except Exception as e:
    print("Warning: user_page blueprint import/register failed:", e)

try:
    from page.list import list_bp
    app.register_blueprint(list_bp, url_prefix='/list')
except Exception as e:
    print("Warning: list_bp blueprint import/register failed:", e)

try:
    from page.detail import detail_page
    app.register_blueprint(detail_page, url_prefix='/')
except Exception as e:
    print("Warning: detail_page blueprint import/register failed:", e)

try:
    from api.user import user_api
    app.register_blueprint(user_api, url_prefix='/')
except Exception as e:
    print("Warning: user_api blueprint import/register failed:", e)


# -----------------------
# AJAX 联想搜索路由：/search/keyword/
# 前端会以 POST 方式发送 kw 与 info，返回 json {code:1,data:[{t_name,num},...]} 或 {code:0}
# -----------------------
@app.route('/search/keyword/', methods=['POST'])
def search_keyword_ajax():
    # 支持 form 或 JSON
    data = {}
    if request.form:
        data = request.form.to_dict()
    else:
        try:
            data = request.get_json(silent=True) or {}
        except Exception:
            data = {}

    kw = (data.get('kw') or data.get('keyword') or '').strip()
    info = (data.get('info') or '').strip()

    if not kw:
        return jsonify({'code': 0, 'msg': '关键字为空'})

    try:
        results = []
        # 先按 community 聚合
        if hasattr(House, 'community'):
            q = (House.query
                 .with_entities(House.community.label('t_name'), func.count(House.id).label('num'))
                 .filter(getattr(House, 'community').like(f"%{kw}%"))
                 .group_by(House.community)
                 .order_by(func.count(House.id).desc())
                 .limit(10))
            for row in q:
                if row.t_name:
                    results.append({'t_name': row.t_name, 'num': int(row.num)})

        # 如果 community 没结果，尝试 address
        if not results and hasattr(House, 'address'):
            q = (House.query
                 .with_entities(House.address.label('t_name'), func.count(House.id).label('num'))
                 .filter(getattr(House, 'address').like(f"%{kw}%"))
                 .group_by(House.address)
                 .order_by(func.count(House.id).desc())
                 .limit(10))
            for row in q:
                if row.t_name:
                    results.append({'t_name': row.t_name, 'num': int(row.num)})

        # 如果仍无结果，尝试 region
        if not results and hasattr(House, 'region'):
            q = (House.query
                 .with_entities(House.region.label('t_name'), func.count(House.id).label('num'))
                 .filter(getattr(House, 'region').like(f"%{kw}%"))
                 .group_by(House.region)
                 .order_by(func.count(House.id).desc())
                 .limit(10))
            for row in q:
                if row.t_name:
                    results.append({'t_name': row.t_name, 'num': int(row.num)})

        if not results:
            return jsonify({'code': 0, 'msg': '未找到相关数据'})

        return jsonify({'code': 1, 'data': results})
    except Exception as e:
        print("search_keyword_ajax error:", e)
        return jsonify({'code': 0, 'msg': '服务器错误'})


# -----------------------
# 首页表单处理路由：/query （支持 GET/POST）
# 表单字段：addr 或 rooms
# -----------------------
@app.route('/query', methods=['GET', 'POST'])
def query_form_handler():
    addr = request.values.get('addr', '').strip()
    rooms = request.values.get('rooms', '').strip()

    if addr:
        # 跳转到 list 蓝图下的 city_house（url_prefix='/list'）
        try:
            return redirect(url_for('list.city_house', city=addr, page=1))
        except Exception:
            # 如果找不到 list.city_house，退回首页
            return redirect('/')
    if rooms:
        # 尝试跳转到 list.search_keyword (如果存在)
        try:
            return redirect(url_for('list.search_keyword', keyword=rooms, page=1))
        except Exception:
            # 回退：把 rooms 当作 city 处理
            try:
                return redirect(url_for('list.city_house', city=rooms, page=1))
            except Exception:
                return redirect('/')

    # 空输入 -> 回首页（用 index_page.index 如果存在）
    try:
        return redirect(url_for('index_page.index'))
    except Exception:
        return redirect('/')


# -----------------------
# 可选：根路径简单检查（方便调试）
# -----------------------
@app.route('/ping')
def ping():
    return "pong"


if __name__ == '__main__':
    # 运行在本地 dev 模式
    app.run(host='127.0.0.1', port=5000, debug=True)
